package com.gua.jbs.controller;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gua.jbs.utility.ExceptionMessage;

/**
 * Filter class that filters all requests to ascertain only authenticated user
 * requests must be served
 * 
 * @author Piyush
 * 
 */
public class AuthenticationFilter implements Filter {

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		// Get the session
		HttpSession session = request.getSession(false);
		String loginUrl = request.getContextPath() + "/pages/jsp/login.jsp";

		// Check whether session is containing any user
		if ((session == null || session.getAttribute("user") == null)&&((!request.getRequestURI().equals(loginUrl)))) {
			String message = ExceptionMessage.ILLEGAL_ACCESS;
			request.setAttribute("message", message);
			response.sendRedirect(request.getContextPath()+"/pages/jsp/login.jsp");
		} else {
			chain.doFilter(req, res);
		}

	}

	@Override
	public void destroy() {

	}
}
